package com.gopay.bis.manager.bank.expay;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.TransUtil;
import com.gopay.bis.common.util.TransUtils;
import com.gopay.bis.manager.bank.BankBindCardManager;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.ExPayBankConstants;
import com.gopay.common.constants.bank.YeePayConstants;
import com.gopay.common.domain.bank.ExPayBaseMessage;
import com.gopay.common.domain.bank.yeepay.expay.YeePayExPayMessage;
import com.gopay.common.domain.bis.BisBankBindCardInfo;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.businesses.ExPayService;

/**
 * 易宝快捷支付manager
 * 
 * @author zhengxue
 * 
 */
public class YeePayExPayManager {
	@Resource(name = "yeePayExPayServiceClient")
	private ExPayService yeePayExPayServiceClient;
	
	@Resource(name = "yeePayConfig")
	private Map<String, String> yeePayConfig;
	
	@Resource(name = "bankBindCardManager")
	BankBindCardManager bankBindCardManager;

	/**
     * 是否需要输入cvv2接口
     * 
     * @param message
     * @return
     * @throws GopayException
     */
    public Object queryCvn(YeePayExPayMessage message) throws GopayException {
        // 用户唯一标识放入用户身份证号
        message.setIdentiid(message.getIdentityCode());
        // 5 用户身份证号
        message.setIdentitype(5);
        BankLogUtils.printExPayManagerQueryCvnSendLog(message);
        YeePayExPayMessage resMsg = (YeePayExPayMessage) yeePayExPayServiceClient.queryCvn(message);
        resMsg.setIsQueryCVN(getQueryCVN(resMsg));
        BankLogUtils.printExPayManagerQueryCvnReturnLog(resMsg);
        return resMsg;
    }
	
	/**
	 * 支付请求(易宝确认支付)
	 * 
	 * @param message
	 * @return
	 * @throws GopayException
	 */
	public Object payment(YeePayExPayMessage message) throws GopayException {
		message = buildMsg(message);
		BankLogUtils.printExPayManagerPaymentSendLog(message);
		YeePayExPayMessage resMsg = (YeePayExPayMessage) yeePayExPayServiceClient
				.payment(message);
		resMsg.setOutStlmCd(message.getOutStlmCd()); // 为了日志输出
		BankLogUtils.printExPayManagerPaymentReturnLog(resMsg);
		return resMsg;
	}

	/**
	 * 易宝回调通知处理
	 * 
	 * @param msg
	 * @return
	 * @throws GopayException
	 */
	public Object verify(YeePayExPayMessage message) throws GopayException {
		BankLogUtils.printExPayManagerVerifySendLog(message);
		YeePayExPayMessage resMsg = (YeePayExPayMessage) yeePayExPayServiceClient
				.verify(message);
		resMsg.setOutStlmCd(message.getOutStlmCd()); // 为了日志输出
		BankLogUtils.printExPayManagerVerifyReturnLog(resMsg, true);
		return resMsg;
	}

	/**
	 * 支付结果查询请求
	 * 
	 * @param msg
	 * @return
	 * @throws GopayException
	 */
	public Object queryOrder(ExPayBaseMessage message) throws GopayException {
		BankLogUtils.printExPayManagerQuerySendLog(message);
		YeePayExPayMessage res = (YeePayExPayMessage) yeePayExPayServiceClient
				.queryOrder(message);
		res.setOutStlmCd(message.getOutStlmCd()); // 为了日志输出
		BankLogUtils.printExPayManagerQueryReturnLog(res);
		return res;
	}

	/**
	 * 构建易宝快捷请求对象
	 * 
	 * @param msg
	 * @return
	 */
	private YeePayExPayMessage buildMsg(YeePayExPayMessage message) {
		String amount = TransUtils.amountConvert2Fen(message.getAmount()
				.toString());
		message.setAmt(Integer.parseInt(amount));
		long time = System.currentTimeMillis() / 1000;
		message.setTranstime((int) time);
		message.setCurrency(156);
		// 1 虚拟行业
		message.setProductcatalog("1");
		message.setProductname("支付-快捷支付");
		// 用户唯一标识放入用户身份证号
		message.setIdentiid(message.getIdentityCode());
		// 5 用户身份证号
		message.setIdentitype(5);
		if (ExPayBankConstants.TERMINAL_TYPE_PHONE.equals(message
				.getTermination())) {
			// 移动端交易
			// 0 ：IMEI
			message.setTerminaltype(0);
			// 终端标识放入IMEI标识
			message.setTerminalid(message.getImei());
		}
		if (ExPayBankConstants.TERMINAL_TYPE_PC
				.equals(message.getTermination())) {
			// PC端交易
			// 3 OTHER
			message.setTerminaltype(3);
			// 终端标识放入浏览器版本号
			message.setTerminalid(message.getBrowser());
		}
		
		// 易宝回调地址
		String bankBusProd = message.getBankBusProd().value;
		if ((BisBankBusinessProd._05.value).equals(bankBusProd)) {
			message.setPayRuturnUrl(yeePayConfig
					.get("YEEPAY.CREDITEXPAY.RETURL"));
			// 信用卡产品操作有效期
//		    String availableDate = message.getAvailableDate(); 
//	        req.setValidDate(availableDate.substring(2,4)+availableDate.substring(0,2));
//			String availableDate = message.getAvailableDate();
//			String y = availableDate.substring(0, 2);
//			String m = availableDate.substring(2, 4);
			message.setAvailableDate(message.getAvailableDate());
			
			String cvv2 = message.getCvv2();
            if (cvv2 == null || "".equals(cvv2)) {
                // 根据卡号查询数据库绑卡信息
                BisBankBindCardInfo bind = bankBindCardManager.getBindCard(message.getIdentiid(), message.getCardNo());
                message.setBindid(bind.getBindId()); // 绑卡ID
            }
		}
		if ((BisBankBusinessProd._15.value).equals(bankBusProd)) {
			message.setPayRuturnUrl(yeePayConfig
					.get("YEEPAY.DEBITEXPAY.RETURL"));
		}
		return message;
	}
	
    /**
     * 易宝查询绑卡信息返回处理
     * 
     * @param message
     * @return
     */
    private String getQueryCVN(YeePayExPayMessage message) {
        String bank = message.getBank();
        String cardNo = message.getCardNo();
        List<BisBankBindCardInfo> listInfo = message.getListInfo(); // 绑卡信息list

        // 循环处理绑卡信息
        for (int i = 0; i < listInfo.size(); i++) {
            BisBankBindCardInfo cardInfo = listInfo.get(i);
            // 根据卡号、手机号确定商户绑卡信息
            if (cardNo.startsWith(cardInfo.getCardTop()) && cardNo.endsWith(cardInfo.getCardLast())) {
                // 根据卡号查询数据库绑卡信息
                BisBankBindCardInfo bind = bankBindCardManager.getBindCard(message.getIdentiid(), cardNo);
                cardInfo.setBankCode(bank);
                cardInfo.setCardNum(cardNo);
                if (bind != null) {
                    // 数据库存在记录则判断bindId，不同则更新
                    if (!cardInfo.getBindId().equals(bind.getBindId())) {
                        bankBindCardManager.updateBindCard(cardInfo);
                    }
                } else {
                    // 不存在则新增
                    bankBindCardManager.addBankBindCard(cardInfo);
                }
                return YeePayConstants.YEEPAY_EXPAY_NOTQUERYCVN;
            }
        }

        return YeePayConstants.YEEPAY_EXPAY_ISQUERYCVN;
    }
}
